package com.chu.cloud.zuul.ratelimit.sms;

import com.chu.cloud.enums.RedisKeyPrefix;
import com.chu.cloud.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 小时短信流控
 *
 * @author: Tianshu.CHU
 * @Date: 2018/9/11 10:52
 */
@Slf4j
public class HourLimitPermits extends SmsPermits {

    @Override
    public String message() {
        return "触发小时级流控";
    }

    @Override
    public int permitOrder() {

        return 0;
    }

    @Override
    public boolean isPermit(String mobile) {
        log.info("--->{}进入小时级别短信流控", mobile);
        Boolean isLock = RedisUtil.get(RedisKeyPrefix.SMS_HOUR_LIMIT_LOCK, mobile, Boolean.class);
        if (Objects.equals(isLock,true)){
            return false;
        }
        String key = RedisKeyPrefix.SMS_HOUR_REQUEST_TIMES.getPrefix() + mobile;
        long times = RedisUtil.incr(key, 1, 60 * 60);
        if (times > HOUR_TIMES){
            RedisUtil.set(RedisKeyPrefix.SMS_HOUR_LIMIT_LOCK, mobile,true,60 * 60);
            return false;
        }
        return true;
    }
}
